<template>
  <div class="app-container">
    <!--  -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="tableInfo.show">
      <el-form-item v-for="item in tableInfo.queryParams" :key="item.key" :label="item.label" :prop="item.prop" v-show="item.status">
        <el-input v-model="item.value" :placeholder="'请输入' + item.label" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-show="tableInfo.show">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd('add')" v-hasPermi="['power:role:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleAdd('activiti')" v-hasPermi="['power:role:add']" disabled>发起流程</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['power:role:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['power:role:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['power:role:export']" disabled>导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList(tableNameOne)"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" stripe @selection-change="handleSelectionChange" v-show="tableInfo.show" header-align="center">
      <el-table-column type="selection" width="55" align="center" />
      <span v-for="item in tableInfo.children" :key="item.key">
        <el-table-column :label="item.label" :width="item.__config__.width" :prop="item.prop" v-if="item.show && item.__config__.type[0] == 'tag'" align="center">
          <template slot-scope="scope">
            <el-tag :type="item.__config__.type[1]">{{ scope.row[item.prop] }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column :label="item.label" :width="item.__config__.width" :prop="item.prop" v-if="item.show && item.__config__.type[0] == 'link'" align="center">
          <template slot-scope="scope">
            <el-button v-if="item.__config__.type[1]=='link-ext'" type="text">
             
            </el-button>
            <el-button v-else-if="item.__config__.type[1]=='link-ins'" type="text" @click="linkFunction()">
             
            </el-button>
           
          </template>
        </el-table-column> -->
        <el-table-column :label="item.label" :width="item.__config__.width" :prop="item.prop" v-else-if="item.show && item.__config__.dict == ''" align="center"> </el-table-column>
        <el-table-column :label="item.label" :width="item.__config__.width" align="center" :prop="item.prop" v-else-if="item.show && item.__config__.dict != ''">
          <!-- <dict-tag :options="dict.type[item.__config__.dict]" :value="scope.row[item.prop]" /> -->
          <template slot-scope="scope">
            <el-tag :type="dictEx[item.__config__.dict][scope.row[item.prop]][1]">{{ dictEx[item.__config__.dict][scope.row[item.prop]][0] }}</el-tag>
          </template>
        </el-table-column>
      </span>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['power:role:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['power:role:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDetails(scope.row)" v-hasPermi="['power:role:remove']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--表单配置详情-->
    <el-dialog :title="title" :visible.sync="detailOpen" width="60%" append-to-body>
      <div class="test-form">
        <parser :key="new Date().getTime()" :form-conf="detailForm" @submit="submitForm" />
      </div>
    </el-dialog>

    <pagination v-show="tableInfo.show" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList(tableNameOne)" />
  </div>
</template>

<script>
import Parser from '@/components/parser/Parser'
import { getInfo } from '@/api/login'
import { publicDelect, publicSubmit, getForm, publicFindById } from '@/api/bpm/form'
import { formatDate, formatDateTime } from '@/utils/index'
import bus from '@/api/eventBus.js'
import { decodeFields } from '@/utils/formGenerator'
import { getDicts } from '@/api/system/dict/data'
export default {
  name: 'Role',
  // dicts: ['sys_normal_disable', 'sys_yes_no', 'sys_user_sex', 'sys_show_hide', 'sys_normal_disable', 'sys_job_status'],
  components: {
    Parser
  },
  props: {
    tableInfo: {
      required: true,
      type: Object
    },
    formInfo: {
      required: true,
      type: Object
    },
    dictEx: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      activitiOpne: false,
      newFormId: 0,
      detailForm: {
        fields: []
      },
      arrTran: [],
      // 表单详情
      detailOpen: false,
      formId: 0,
      tableNameOne: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 数据范围选项
      dataScopeOptions: [
        {
          value: '1',
          label: '全部数据权限'
        },
        {
          value: '2',
          label: '自定数据权限'
        },
        {
          value: '3',
          label: '本部门数据权限'
        },
        {
          value: '4',
          label: '本部门及以下数据权限'
        },
        {
          value: '5',
          label: '仅本人数据权限'
        }
      ],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
        roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
      }
    }
  },

  created() {
    bus.$on('tablename', (val) => {
      this.tableNameOne = val
      this.getList(val)
    })
    bus.$on('formId', (val) => {
      this.formId = val
    })
  },
  watch: {
    formInfo: {
      handler(val) {
        this.tableNameOne = val.formRef
        this.getList(val.formRef)
      },
      deep: true
    }
  },
  methods: {
    test(val) {},
    arrTransform(val) {
      const sign1 = console.log('test')

      return sign1[0]
    },
    dictFunction(dict) {
      getDicts(dict).then((response) => {
        var dictOne = {}
        for (let index = 0; index < response.data.length; index++) {
          dictOne[response.data[index].dictValue] = [response.data[index].dictLabel, response.data[index].listClass]
        }
        this.dictEx[response.data[0].dictType] = dictOne
      })
    },
    /** 查询列表 */
    getList(val) {
      this.loading = true
      for (var index in this.tableInfo.queryParams) {
        let keyValue = {}
        if (this.tableInfo.queryParams[index].value == 'undefined') {
          keyValue[this.tableInfo.queryParams[index].prop] = undefined
        } else {
          keyValue[this.tableInfo.queryParams[index].prop] = this.tableInfo.queryParams[index].value
        }

        this.queryParams = { ...this.queryParams, ...keyValue }
      }

      var sub = { find: {}, limit: {} }
      sub = { ...sub, ...{ tableName: val } }

      for (var item in this.queryParams) {
        if (item != 'pageNum' && item != 'pageSize' && item != 'params' && this.queryParams[item] != undefined && this.queryParams[item] != '') {
          let keyValue = {}
          keyValue[item] = this.queryParams[item]
          sub.find = { ...sub.find, ...keyValue }
        } else if (item == 'pageNum' || item == 'pageSize') {
          let keyValue = {}
          keyValue[item] = this.queryParams[item]
          sub.limit = { ...sub.limit, ...keyValue }
        }
      }

      publicSubmit('/Sleepfish/find', 'post', sub).then((response) => {
        var la = []
        var laTime = []
        for (let index = 0; index < this.tableInfo.children.length; index++) {
          if (this.tableInfo.children[index].__config__.type[0] == 'raw') {
            continue
          }
          if (this.tableInfo.children[index].__config__.type[1] == 'date') {
            la.push(this.tableInfo.children[index].prop)
          } else if (this.tableInfo.children[index].__config__.type[1] == 'dateTime') {
            laTime.push(this.tableInfo.children[index].prop)
          }
        }

        response.data.map((item) => {
          // item.createTime = formatDate(item.createTime)
          // item.updateTime = formatDate(item.updateTime)
          for (let index = 0; index < la.length; index++) {
            item[la[index]] = formatDate(item[la[index]])
          }
          for (let index = 0; index < laTime.length; index++) {
            item[laTime[index]] = formatDateTime(item[laTime[index]])
          }
        })

        this.roleList = response.data

        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList(this.tableNameOne)
    },
    /** 重置按钮操作 */
    resetQuery() {
      for (var index in this.tableInfo.queryParams) {
        this.tableInfo.queryParams[index].value = undefined
      }
      this.getList(this.tableNameOne)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd(name) {
      if (name == 'add') {
        getForm(this.formId).then((response) => {
          // 设置值
          const data = response.data
          this.detailForm = {
            ...JSON.parse(data.conf),
            fields: decodeFields(data.fields)
          }
          // 弹窗打开
          this.title = '新增数据'
          this.detailOpen = true
          this.activitiOpne = false
        })
      } else if (name == 'activiti') {
        getForm(this.formId).then((response) => {
          // 设置值
          const data = response.data
          this.detailForm = {
            ...JSON.parse(data.conf),
            fields: decodeFields(data.fields)
          }
          // 弹窗打开
          this.title = '提交流程'
          this.detailOpen = true
          this.activitiOpne = true
        })
      }
    },

    handleDetails(row) {
      var id = row.id
      if (id == undefined) {
        id = this.ids[0]
      }

      var sqls = '/Sleepfish/findById?tableName=' + this.tableNameOne + '&id='
      getForm(this.formId).then((response) => {
        // 设置值
        const data = response.data

        this.detailForm = {
          ...JSON.parse(data.conf),
          disabled: true, // 表单禁用
          formBtns: false, // 按钮隐藏
          fields: decodeFields(data.fields)
        }
        // 弹窗打开
        this.title = '修改数据'
        publicFindById(sqls, 'get', id).then((response) => {
          this.detailForm.fields.forEach((item) => {
            const val = response.data[0][item.__vModel__]

            if (val) {
              item.__config__ = { ...item.__config__, ...{ defaultValue: val } }
            }
          })
        })
        setTimeout(() => {
          this.newFormId = id
          this.detailOpen = true
        }, 550)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      var id = row.id
      if (id == undefined) {
        id = this.ids[0]
      }

      var sqls = '/Sleepfish/findById?tableName=' + this.tableNameOne + '&id='

      getForm(this.formId).then((response) => {
        // 设置值

        const data = response.data

        this.detailForm = {
          ...JSON.parse(data.conf),
          fields: decodeFields(data.fields)
        }

        // 弹窗打开
        this.title = '修改数据'
        publicFindById(sqls, 'get', id).then((response) => {
          this.detailForm.fields.forEach((item) => {
            const val = response.data[0][item.__vModel__]
            if (val) {
              item.__config__ = { ...item.__config__, ...{ defaultValue: val } }
            }
          })
        })
        setTimeout(() => {
          this.newFormId = id
          this.detailOpen = true
        }, 500)
      })
    },

    /** 提交按钮 */
    submitForm(params) {
      if (this.title == '修改数据') {
        getInfo().then((response) => {
          params.values = { ...params.values, ...{ updateBy: response.user.userName } }
          params.values = { ...params.values, ...{ id: this.newFormId } }

          publicSubmit('/Sleepfish/update', 'post', params).then((response) => {
            this.detailOpen = false
            this.getList(this.tableNameOne)
            this.$modal.msgSuccess('修改成功')
          })
        })
      } else if (this.title == '新增数据') {
        getInfo().then((response) => {
          params.values = { ...params.values, ...{ createBy: response.user.userName } }
          publicSubmit('/Sleepfish/save', 'post', params).then((response) => {
            this.detailOpen = false
            this.getList(this.tableNameOne)
            this.$modal.msgSuccess('新增成功')
          })
        })
      } else if (this.title == '提交流程') {
        // // 设置表单禁用
        // const conf = params.conf
        // conf.disabled = true // 表单禁用
        // conf.formBtns = false // 按钮隐藏
        // // 提交表单，创建流程
        // const variables = params.values
        // getInfo().then((response) => {
        //   params.values = { ...params.values, ...{ createBy: response.user.userName } }
        //   publicSubmit('/Sleepfish/save', 'post', params).then((response) => {
        //     createProcessInstance({
        //       processDefinitionId: this.selectProcessInstance.id,
        //       variables: variables
        //     })
        //       .then((response) => {
        //         this.$modal.msgSuccess('发起流程成功')
        //         // 关闭当前窗口
        //         this.$tab.closeOpenPage()
        //         this.$router.go(-1)
        //       })
        //       .catch(() => {
        //         conf.disabled = false // 表单开启
        //         conf.formBtns = true // 按钮展示
        //       })
        //   })
        // })
      }

      // this.$refs['form'].validate((valid) => {
      //   if (valid) {
      //     if (this.form.roleId != undefined) {
      //       updateRole(this.form).then((response) => {
      //         this.$modal.msgSuccess('修改成功')
      //         this.open = false
      //         this.getList(this.tableNameOne)
      //       })
      //     } else {
      //       addRole(this.form).then((response) => {
      //         this.$modal.msgSuccess('新增成功')
      //         this.open = false
      //         this.getList(this.tableNameOne)
      //       })
      //     }
      //   }
      // })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      var sqls = '/Sleepfish/delect?tableName=' + this.tableNameOne + '&ids='

      this.$modal
        .confirm('是否确认删除角色编号为"' + ids + '"的数据项？')
        .then(function () {
          return publicDelect(sqls, 'delete', ids)
        })
        .then(() => {
          this.getList(this.tableNameOne)
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'power/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>

<style scoped></style>
